package com.sc.autotask.core.api.web;

import com.github.pagehelper.PageInfo;
import com.sc.autotask.entity.JobUpdate;
import com.sc.autotask.core.job.BaseJob;
import com.sc.autotask.core.service.JobService;
import com.sc.common.annotations.OperationLog;
import com.sc.common.annotations.WebApi;
import com.sc.common.dto.PageDto;
import com.sc.common.dto.WebResponseDto;
import com.sc.autotask.entity.jobandtrigger.QrtzJobAndTriggerList;
import com.sc.autotask.entity.jobandtrigger.QrtzJobAndTriggerSearch;
import com.sc.common.enums.OperationLogEnum;
import org.quartz.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * Created by wust on 2019/6/13.
 */
@WebApi
@RequestMapping("/web/JobController")
@RestController
public class JobController {
    @Autowired
    private JobService jobServiceImpl;

    @Autowired
    private SchedulerFactoryBean schedulerFactoryBean;


    @RequestMapping(value = "/listPage",method = RequestMethod.POST)
    public WebResponseDto listPage(@RequestBody QrtzJobAndTriggerSearch search){
        WebResponseDto responseDto = new WebResponseDto();

        List<QrtzJobAndTriggerList> list =  jobServiceImpl.selectByPageNumSize(search,search.getPageDto().getPageNum(),search.getPageDto().getPageSize());
        PageInfo page = new PageInfo(list);
        PageDto pageDto = new PageDto();
        BeanUtils.copyProperties(page,pageDto);
        responseDto.setPage(pageDto);
        responseDto.setLstDto(list);
        return responseDto;
    }

    /**
     * 暂停
     * @param entity
     * @return
     */
    @OperationLog(moduleName= OperationLogEnum.MODULE_AUTOTASK_JOB,businessName="暂停",operationType= OperationLogEnum.Update)
    @RequestMapping(value = "/pause",method = RequestMethod.POST)
    public WebResponseDto pause(@RequestBody JobUpdate entity){
        WebResponseDto mm = new WebResponseDto();
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        try {
            JobKey jobKey = new JobKey(entity.getJobName(), entity.getJobGroupName());
            boolean isExists = scheduler.checkExists(jobKey);
            if (isExists) {
                scheduler.pauseJob(jobKey);
            }
        }catch (SchedulerException e){
            mm.setFlag(WebResponseDto.INFO_WARNING);
            mm.setMessage("暂停作业失败");
            return mm;
        } catch (Exception e) {
            mm.setFlag(WebResponseDto.INFO_WARNING);
            mm.setMessage("暂停作业失败");
            return mm;
        }
        return mm;
    }

    /**
     * 恢复
     * @param entity
     * @return
     */
    @OperationLog(moduleName= OperationLogEnum.MODULE_AUTOTASK_JOB,businessName="恢复",operationType= OperationLogEnum.Update)
    @RequestMapping(value = "/resume",method = RequestMethod.POST)
    public WebResponseDto resume(@RequestBody JobUpdate entity){
        WebResponseDto mm = new WebResponseDto();
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        try {
            JobKey jobKey = new JobKey(entity.getJobName(), entity.getJobGroupName());
            boolean isExists = scheduler.checkExists(jobKey);
            if (isExists) {
                scheduler.resumeJob(jobKey);
            }
        }catch (SchedulerException e){
            mm.setFlag(WebResponseDto.INFO_WARNING);
            mm.setMessage("恢复作业失败");
            return mm;
        } catch (Exception e) {
            mm.setFlag(WebResponseDto.INFO_WARNING);
            mm.setMessage("恢复作业失败");
            return mm;
        }
        return mm;
    }

    @OperationLog(moduleName= OperationLogEnum.MODULE_AUTOTASK_JOB,businessName="修改",operationType= OperationLogEnum.Update)
    @RequestMapping(value = "",method = RequestMethod.POST)
    public WebResponseDto update(@RequestBody JobUpdate entity){
        WebResponseDto mm = new WebResponseDto();
        Scheduler scheduler = schedulerFactoryBean.getScheduler();

        try {
            JobKey jobKey = new JobKey(entity.getJobName(), entity.getJobGroupName());
            boolean isExists = scheduler.checkExists(jobKey);
            if (isExists) {
                scheduler.deleteJob(jobKey);
            }

            //构建job信息
            JobDetail jobDetail = JobBuilder.newJob(getClass(entity.getJobClassName()).getClass()).withIdentity(entity.getJobName(), entity.getJobGroupName()).build();

            //表达式调度构建器(即任务执行的时间)
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(entity.getCronExpression());

            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(entity.getJobName(), entity.getJobGroupName()).withSchedule(scheduleBuilder).build();

            scheduler.scheduleJob(jobDetail, trigger);

            if(!scheduler.isShutdown()){
                scheduler.start();
            }
        }catch (SchedulerException e){
            mm.setFlag(WebResponseDto.INFO_WARNING);
            mm.setMessage("修改作业失败");
            return mm;
        } catch (Exception e) {
            mm.setFlag(WebResponseDto.INFO_WARNING);
            mm.setMessage("修改作业失败");
            return mm;
        }
        return mm;
    }


    @OperationLog(moduleName= OperationLogEnum.MODULE_AUTOTASK_JOB,businessName="删除",operationType= OperationLogEnum.Delete)
    @RequestMapping(value = "/{jobName}/{jobGroupName}",method = RequestMethod.DELETE)
    public WebResponseDto delete(@PathVariable String jobName, @PathVariable String jobGroupName){
        WebResponseDto mm = new WebResponseDto();
        Scheduler scheduler = schedulerFactoryBean.getScheduler();

        try {
            JobKey jobKey = new JobKey(jobName, jobGroupName);
            boolean isExists = scheduler.checkExists(jobKey);

            if (isExists) {
                scheduler.deleteJob(jobKey);
            }
        }catch (SchedulerException e){
            mm.setFlag(WebResponseDto.INFO_WARNING);
            mm.setMessage("删除作业失败");
            return mm;
        }
        return mm;
    }


    @OperationLog(moduleName= OperationLogEnum.MODULE_AUTOTASK_JOB,businessName="初始化",operationType= OperationLogEnum.Insert)
    @RequestMapping(value = "/init",method = RequestMethod.POST)
    public WebResponseDto init(){
        WebResponseDto responseDto = new WebResponseDto();
        return responseDto;
    }



    private static BaseJob getClass(String classname) throws Exception {
        Class<?> class1 = Class.forName(classname);
        return (BaseJob)class1.newInstance();
    }
}
